from django.core.validators import EmailValidator
from rest_framework import serializers
from apps.user.models import User, UserAddress
from utils.password_encode import get_md5


class UserSerializer(serializers.ModelSerializer):
    gender_display = serializers.CharField(source='get_gender_display', read_only=True)

    class Meta():
        model = User
        fields = "__all__"
        extra_kwargs = {
            'name': {'required': True, 'max_length': 8, 'min_length': 2},
            'email': {'required': True, 'validators': [EmailValidator(message='邮箱格式错误')]},
            'gender': {'required': True, 'write_only': True},
            'mobile': {'required': True},
            'password': {'required': True, 'write_only': True, 'min_length': 6, 'max_length': 60},
        }

    def to_representation(self, instance):
        representation = super(UserSerializer, self).to_representation(instance)
        print(instance.get_gender_display())
        representation['gender_display'] = instance.get_gender_display()
        return representation

    def validate_mobile(self, value):
        if len(value) != 11:
            raise serializers.ValidationError('手机号输入错误')
        else:
            return value

    def create(self, validated_data):
        # print(validated_data)  # {'name': '叫我DPT', 'gender': 1, 'email': '4659753100@QQ.com', 'mobile': '13191273507', 'password': '123456'}
        if 'password' in validated_data:
            validated_data['password'] = get_md5(validated_data['password'])  # md5加密
        result = User.objects.create(**validated_data)
        return result

class UserAddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAddress
        fields = '__all__'